/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmAttachmentController
 * 项目资料
 *
 * 修改纪录
 * 2020-05-16 版本：1.0 fanzhiming 创建。
 * @version 版本：1.0
 * @author 作者：fanzhiming
 * 创建日期：2020-05-16
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.pm.controller.auto.PmAttachmentControllerAuto;
import com.topscomm.pm.pojo.PmAttachmentEntity;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst;

import java.nio.file.Files;
import java.util.HashMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: fanzhiming
 * @date: 2020-05-16
 * @description:项目资料Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/attachment")
public class PmAttachmentController extends PmAttachmentControllerAuto implements IPmAttachmentController {

	private final static String projectSourceType = "PmProjectAttachment";

	/**
	 * @author: fanzhiming
	 * @date: 2020-05-16
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" cboattachment.enabled=1 and cboattachment.sourcetype = '{0}' ", projectSourceType);
		// 文件名称 模糊查询
		if (paraMap.containsKey("qry_displayname")) {
			String value = paraMap.get("qry_displayname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and displayname like '%{0}%' ", value);
		}
		// 关联项目
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = '{0}' ", value);
		}
		// 资料权限
		String usercode = this.getUserBean().getUser().getCode();
		if (paraMap.containsKey("qry_permissiontype")) {
			String value = paraMap.get("qry_permissiontype").toString();
			if (!StringUtil.isEmpty(value)) {
				if ("1".equals(value)) {// 公开
					sql.appendSingle(" and extendfield1 = '1' ", value);
				} else { // 只对项目组可见
					sql.appendSingle(" and exists (select pmteam.id from pmteam where pmteam.projectid = cboattachment.sourceid");
					sql.appendSingle(" and pmteam.usercode = '{0}')", usercode);
				}
			} else { // 不选择的话，默认把公开和能看到的资料查询出来
				sql.appendSingle(" and (extendfield1 = '1' or (extendfield1 = '2' and exists (select pmteam.id from pmteam");
				sql.appendSingle(" where pmteam.projectid = cboattachment.sourceid and pmteam.usercode = '{0}')))", usercode);
			}
		} else { // 不传值，默认把公开和能看到的资料查询出来
			sql.appendSingle(" and (extendfield1 = '1' or (extendfield1 = '2' and exists (select pmteam.id from pmteam");
			sql.appendSingle(" where pmteam.projectid = cboattachment.sourceid and pmteam.usercode = '{0}')))", usercode);
		}
		// 资料类型
		if (paraMap.containsKey("qry_datatype")) {
			String value = paraMap.get("qry_datatype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and extendfield2 = '{0}' ", value);
		}
		sql .appendSingle(this.spellingSqlForProject(paraMap, "cboattachment","sourceid","id"));
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", this.getUserBean());
//			if (StringUtil.isEmpty(dataPession)) {
//				sql.appendSingle(" and " + MisStringUtil.createWhereByUsercodeFromProject(this.getUserBean().getUser(), "projectid", service.getDao().getTableName()));
//			}
			if (StringUtil.isEmpty(dataPession)) {
				sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
						this.getUserBean().getUser(), "sourceid",
						service.getDao().getTableName()) + ")");
			}
			else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: fanzhiming
	 * @date: 2020-05-16
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 计算文件个数
	  **/
	@GetMapping({"/calculateCount"})
	public ResponseResult<Object> calculateCount(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String id = paraMap.get("id").toString();
		int count = 0;
		if (!StringUtil.isEmpty(id)) {
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" id = '{0}' and displayname is not null", id);
			count = this.service.getCount(sql.toString());
		}
		return ResponseResult.ok(count);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 查询附件列表
	  **/
	@GetMapping({"/queryAttachmentList"})
	public ResponseResult<Object> queryAttachmentList(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String id = paraMap.get("id").toString();
		List<PmAttachmentEntity> list = new ArrayList<>();
		if (!StringUtil.isEmpty(id)) {
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" id = '{0}' and displayname is not null", id);
			List<PmAttachmentEntity> pmAttachmentList = this.service.queryByWhere(sql.toString());
			list.addAll(pmAttachmentList);
		}
		return ResponseResult.ok(list);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 上传文件
	  **/
	@PostMapping({"/upload"})
	public ResponseResult<Object> upload(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Map<String, Object> paraMap) {
		File attachFile = null;

		ResponseResult var5;
		try {
			if (file == null || file.getSize() <= 0L) {
				ResponseResult var11 = ResponseResult.error("找不到合法的文件");
				return var11;
			}

			paraMap = BaseUtil.decodeSecureMap(paraMap);
			attachFile = this.multipartFileToFile(file);
			Map<String, Object> map = this.service.executeUpload(paraMap, attachFile);
			var5 = ResponseResult.ok(map);
			return var5;
		} catch (Exception var9) {
			var5 = ResponseResult.error(var9.getMessage());
		} finally {
			if (attachFile != null) {
				attachFile.delete();
			}

		}

		return var5;
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 下载文件
	  **/
	@PostMapping({"/download"})
	public void download(@RequestBody Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Map<String, Object> resultMap = this.service.executeDownload(paraMap);
			String fileName = ConvertUtil.convertToString(resultMap.get("attFileName"));
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			InputStream inStream = BaseUtil.convertByteToStream((byte[])((byte[])resultMap.get("attInputStream")));
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];

			int len;
			while((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}

			inStream.close();
		} catch (Exception var10) {
			throw new BusinessException(var10);
		}
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 展示文件
	  **/
	@PostMapping({"/display"})
	public void display(@RequestBody Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Map<String, Object> resultMap = this.service.executeDownload(paraMap);
			String fileName = ConvertUtil.convertToString(resultMap.get("attFileName"));
			String ext = FileUtil.getExtention(fileName).toLowerCase();
			String contentType = "";
			if (".pdf".equals(ext)) {
				contentType = "application/pdf";
			} else if (".doc".equals(ext)) {
				contentType = "application/msword";
			} else if (".docx".equals(ext)) {
				contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
			} else if (".mp3".equals(ext)) {
				contentType = "audio/mpeg";
			} else if (".jpg".equals(ext)) {
				contentType = "image/jpeg";
			} else if (".txt".equals(ext)) {
				contentType = "text/plain";
			} else if (".ppt".equals(ext)) {
				contentType = "application/vnd.ms-powerpoint";
			} else if (".pptx".equals(ext)) {
				contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
			} else if (".xls".equals(ext)) {
				contentType = "application/vnd.ms-excel";
			} else if (".xlsx".equals(ext)) {
				contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
			} else {
				contentType = "Application/Octet-stream";
			}

			response.setContentType(contentType);
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Accept-Ranges", "bytes");
			InputStream inStream = BaseUtil.convertByteToStream((byte[])((byte[])resultMap.get("attInputStream")));
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];

			int len;
			long fileLen;
			for(fileLen = 0L; (len = inStream.read(bytes)) != -1; fileLen += (long)len) {
				outStream.write(bytes, 0, len);
			}

			response.addHeader("Content-Length", "" + fileLen);
			inStream.close();
		} catch (Exception var14) {
			throw new BusinessException(var14);
		}
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 删除文件
	  **/
	@DeleteMapping({"/deleteFile"})
	public ResponseResult<Object> deleteFile(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String[] arrayId = ConvertUtil.convertToString(paraMap.get("ids")).split(",");
			this.service.deleteFile(arrayId);
			return ResponseResult.ok("删除成功");
		} catch (Exception var3) {
			return this.handleControllerException(var3);
		}
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 将Multipartfile转换为File
	  **/
	private File multipartFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if (file != null && file.getSize() > 0L) {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			this.inputStreamToFile(ins, toFile);
			ins.close();
		} else {
			file = null;
		}

		return toFile;
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 将流信息写入到文件中
	  **/
	private void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			byte[] buffer = new byte[8192];
			int bytesRead;
			while((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}

			os.close();
			ins.close();
		} catch (Exception var6) {
			var6.printStackTrace();
		}
	}


	@Override
	@GetMapping({"/list"})
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			paraMap.put("whereSql",sqlWhere);
			int totalCount = this.service.getCount(paraMap,"getPmAttachmentAndProjectCount");
			List<Map<String, Object>> tempList = null;
			HashMap<String, Object> paraMap2 = new HashMap<>();
			paraMap2.put("curPageIndex",query.getCurrentPage());
			int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
			paraMap2.put("begincount",beginCount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", query.getSidx());
			paraMap2.put("sord", query.getSord());
			paraMap2.put("whereSql", sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(paraMap2,"getPmAttachmentAndProject");
			} else {
				tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
			}
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}

}

